package com.spark.trouble

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.google.gson.Gson
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.*
import com.spark.common.model.ResultModel
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.common.widget.RejectAlert
import kotlinx.android.synthetic.main.frag_ht_upgrade.*

/**
 * 待办-隐患升级
 */
class HTUpgradeFragment : BaseFragment() {
    private var taskId = ""

    companion object {
        fun newInstance(taskId: String): HTUpgradeFragment {
            val target = HTUpgradeFragment()
            val args = Bundle()
            args.putString("taskId", taskId)
            target.arguments = args
            return target
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_ht_upgrade
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        arguments?.apply {
            getString("taskId")?.apply {
                this@HTUpgradeFragment.taskId = this
                fetchAgencyVerify(taskId)
            }
        }
        // 驳回
        tv_reject.setOnClickListener {
            activity?.apply {
                RejectAlert.Builder(this, "驳回理由", "请输入驳回理由")
                        .affirm { d, str ->
                            if (str.isNullOrBlank())
                                alert("请输入驳回理由")
                            else {
                                d.dismiss()
                                submitAgencyRejectVerify(this@HTUpgradeFragment.taskId, str!!)
                            }
                        }
                        .cancel { d, i ->
                            d.dismiss()
                        }
                        .create()
                        .show()
            }
        }
        // 通过
        btn_resolve.setOnClickListener { submitAgencyVerify(taskId)}
    }

    /**
     * restore
     */
    private fun restore(
            handleMan: String,
            judgeReason: String
    ) {
        tv_handle_man.text = handleMan
        et_judge_reason.setText(judgeReason)
    }

    /**
     * [待办] 所有任务 -> 待审核/待确认/隐患升级 -> 驳回
     */
    @SuppressLint("CheckResult")
    private fun submitAgencyRejectVerify(taskId: String, rejectReason: String) {
        val params = mutableMapOf("taskId" to taskId, "refuseReason" to rejectReason)
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_alltask_submit_reject2_verify_confirm}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )
    }

    /**
     * [待办] -> 隐患升级 -> 待审核
     */
    @SuppressLint("CheckResult")
    private fun submitAgencyVerify(taskId: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_major_submit_verify}", mutableMapOf("taskId" to taskId, "approveState" to "2").toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...«")
                        }
                )
    }

    /**
     * [待办] 隐患升级 -> 待审核
     */
    @SuppressLint("CheckResult")
    private fun fetchAgencyVerify(taskId: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agencty_major_fetch_verify}", mutableMapOf("taskId" to taskId).toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, MajorUpgradeInfoModel::class.java)?.apply {
                                if (code == "200" && resultMaps.isNotEmpty()) {
                                    resultMaps[0].apply {
                                        restore(processName, trouble_content)
                                    }
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading()
                        }
                )
    }

}


data class MajorUpgradeInfoModel(
        var msg: String = "", // 成功
        var code: String = "", // 200
        var data: Any = Any(), // null
        var resultMaps: List<ResultMap> = listOf()
) {

    data class ResultMap(
            var source_processor_id: Int = 0, // 18
            var trouble_level: String = "", // 中警
            var solution_type: Int = 0, // 0
            var task_id: Int = 0, // 2327
            var process_time: Long = 0, // 1533268800000
            var trouble_content: String = "", // As
            var responsible_user_id: Int = 0, // 20
            var fatal: Boolean = false, // false
            var approve_remark: String = "", // 保存驳回理由
            var responsible_money: Int = 0, // 100
            var processName: String = "", // 张无忌
            var rectify_day: Int = 0, // 0
            var processor_id: Int = 0, // 18
            var responsible_leader_name: String = "", // 闫老师
            var acceptor_name: String = "", // 任建
            var process_type: Int = 0, // 1
            var solution_content: String = "", // QR
            var source_processor_name: String = "", // 张无忌
            var technician_name: String = "", // 张峰
            var source_score: Int = 0, // 2
            var approver_id: Int = 0, // 21
            var approver_name: String = "", // 闫老师
            var source_money: Int = 0, // 100
            var main_id: Int = 0, // 2326
            var source_category: String = "", // 1
            var responsible_leader_id: Int = 0, // 21
            var technician_id: Int = 0, // 19
            var accept_reason: String = "", // we
            var responsible_user_name: String = "", // 袁建
            var acceptor_id: Int = 0, // 22
            var responsible_score: Int = 0, // 2
            var source_id: Int = 0, // 1
            var responsible_department_id: Int = 0, // 23
            var responsible_department_name: String = "", // 铜川福美煤矿
            var source_description: String = "" // 测试隐患源
    )
}